extends Label


class_name PropertyUiLabel
"""
监听并格式化显示的属性 "Exp:${value}/${max_value} Lv:${level}"
"""


@export var attr_name: String = ""
@export var character: ICharacterComponent = null


var __format_text: String = ""
var __property_list: Array = []


func __check_exports() -> Dictionary:
    return {
        "character": func (): return character != null
    }

func _get_configuration_warnings():
    return IComponent.editor_warnings(self)

func _ready() -> void:
    var attr: Attribute = character.get_attribute(attr_name)
    if attr:
        attr.event_property_changed.connect(on_value_changed)

        __format_text = text
        __property_list = extract_bracketed_content(__format_text)
        update_value("", attr.value)

func extract_bracketed_content(input: String) -> Array:
    var regex = RegEx.new()
    regex.compile("[{\\$](.*?)[}]")
    var matches = []
    for r in regex.search_all(input):
        var v = r.get_string()
        matches.append(v.substr(2, v.length() - 3))
    return matches

func update_value(v_name: String, value: int) -> void:
    var display_text = __format_text
    for p in __property_list:
        display_text = NodeHelper.replace_variable(display_text, {p: value})
    text = display_text

func on_value_changed(attr: Attribute, property: String, new_value: int) -> void:
    if __property_list.has(property):
        update_value(property, new_value)
